package com.isunland.managesystem.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.AttendanceListAdapter;
import com.isunland.managesystem.adapter.AttendanceListAdapter.Callback;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.AttendanceDetail;
import com.isunland.managesystem.entity.AttendanceListOriginal;
import com.isunland.managesystem.entity.AttendanceParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

public class AttendanceListFragment extends BaseListFragment implements Callback {

  /**
   * 当前用户查看考勤列表,可以删除,显示考勤分组等
   */
  public static final int TYPE_USER = 1;
  /**
   * 作业任务考勤核查,不可删除,无法查看地图等
   */
  public static final int TYPE_LOCALE_WORK = 2;
  private AttendanceListAdapter mAdapter;
  //private int mCurrentPage = 1;// 请求第几页的数据.

  private Callbacks mCallbacks;
  private String mJobNos;
  private String mStartTime;
  private String mEndTime;
  private int mType;
  private AttendanceParams mParams;
  /** 打卡类型 */
  private String mSignType;

  @Override public void onAttach(Context activity) {
    super.onAttach(activity);
    mCallbacks = (Callbacks) activity;
  }

  @Override public void onDetach() {
    super.onDetach();
    mCallbacks = null;
  }

  public void initData() {
    //设置启动分页
    setIsPaging(true);
    mParams = mBaseParams instanceof AttendanceParams ? (AttendanceParams) mBaseParams
        : new AttendanceParams();
    mJobNos = mParams.getJobNos();
    mStartTime = mParams.getStartDate();
    mEndTime = mParams.getEndDate();
    mType = mParams.getTypeFrom();
    String title = mParams.getTitle();
    setTitleCustom(title);
    mAdapter = new AttendanceListAdapter(getActivity(), new ArrayList<AttendanceDetail>(), this,
        initType(mType));
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setListAdapter(mAdapter);
  }

  @Override public String getUrl() {

    return ApiConst.URL_SIGN_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("jobNos", mJobNos);
    //params.put("begindate", mStartTime);
    params.put("begincheckTime", mStartTime);
    //params.put("enddate", mEndTime);
    params.put("endcheckTime", mEndTime);
    params.put("checkType", mSignType);
    return params.getParams();
  }

  @Override public void resolveResponse(String arg0) {

    AttendanceListOriginal attendanceListOriginal =
        new Gson().fromJson(arg0, AttendanceListOriginal.class);
    if (isPaging() && getCurrentPage() == 1) mAdapter.clear();
    // noinspection unchecked
    mAdapter.addAll(attendanceListOriginal.getList());
    mAdapter.notifyDataSetChanged();
    //updateSignInfo();
  }

  @Override public boolean isNeedRoleType() {
    //现场作业任务,不传roleTypeFlag.返回 false.
    return mType != TYPE_LOCALE_WORK;
  }

  private int initType(int type) {
    if (type == TYPE_USER) return AttendanceListAdapter.TYPE_USER;
    if (type == TYPE_LOCALE_WORK) return AttendanceListAdapter.TYPE_LOCALE_WORK;
    return TYPE_USER;
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_sign_list, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_map:
        if (mType == TYPE_LOCALE_WORK) {
          AttendanceMapLocalWorkActivity.newInstance(this, getActivity(), 0, mParams);
          return true;
        } else {
          Intent map = new Intent(getActivity(), AttendanceMapActivity.class);
          startActivity(map);
          return true;
        }
      case R.id.menu_item_time_today:
        mStartTime = MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE);
        mEndTime = MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE);
        refreshFromTop();
        break;
      case R.id.menu_item_time_week:
        mStartTime =
            MyDateUtil.format(MyDateUtil.getBeginWeekByDate(new Date()), MyDateUtil.TYPE_DATE);
        mEndTime = MyDateUtil.format(MyDateUtil.getEndWeekByDate(new Date()), MyDateUtil.TYPE_DATE);
        refreshFromTop();
        break;
      case R.id.menu_item_time_month:
        mStartTime = MyDateUtil.getBeforeMonthFirstDay(0);
        mEndTime = MyDateUtil.getBeforeMonthLastDay(0);
        refreshFromTop();
        break;
      case R.id.menu_item_time_nolimit:
        mStartTime = null;
        mEndTime = null;
        refreshFromTop();
        break;
      case R.id.menu_item_type_in:
        mSignType = "in";
        refreshFromTop();
        break;
      case R.id.menu_item_type_out:
        mSignType = "out";
        refreshFromTop();
        break;
      case R.id.menu_item_type_keep:
        mSignType = "keep";
        refreshFromTop();
        break;
      case R.id.menu_item_type_nolimit:
        mSignType = "";
        refreshFromTop();
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  public void refresh() {
    //刷新清空筛选条件
    mStartTime = null;
    mEndTime = null;
    mSignType = "";
    refreshFromTop();
  }

  //@Override
  //public void onListItemClick(ListView l, View v, int position, long id) {
  //点击滑动删除
  //LinearLayout root = ((LinearLayout) (mListview.getChildAt(position - mListview.getFirstVisiblePosition())));
  //SwipeLayout swipe= (SwipeLayout) root.findViewById(R.id.swipe);
  //swipe.toggle();

  //    super.onListItemClick(l, v, position, id);
  //}

  private void showDialog(final AttendanceDetail item) {
    new AlertDialog.Builder(getActivity()).setTitle("删除打卡记录")
        .setMessage("打卡记录删除后将不可恢复,是否确认?")
        .setPositiveButton("确认", new OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            volleypostDelete(item);
          }
        })
        .setNegativeButton("取消", new OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            // Auto-generated method stub

          }
        })
        .show();
  }

  // private class MyModeCallback implements ListView.MultiChoiceModeListener
  // {
  //
  // @Override
  // public boolean onCreateActionMode(ActionMode mode, Menu menu) {
  // // actionmode的菜单处理
  // MenuInflater inflater = getActivity().getMenuInflater();
  // inflater.inflate(R.menu.menu_delete_multi, menu);
  //
  // return true;
  // }
  //
  // @Override
  // public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
  //
  // return false;
  // }
  //
  // @Override
  // public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
  // switch (item.getItemId()) {
  // case R.id.menu_item_delete_multi:
  // SparseBooleanArray positions = mListview.getCheckedItemPositions();
  // if (positions.size()==0) {
  // ToastUtil.show("请选择要删除的考勤记录");
  // return true;
  // }
  // for (int i = 0; i < positions.size(); i++) {
  // mAdapter.remove(mAdapter.getItem(positions.keyAt(i) - 1));
  //
  // }
  // mAdapter.notifyDataSetChanged();
  //
  // break;
  //
  // default:
  // break;
  // }
  //
  //
  //
  // return true;
  // }
  //
  // @Override
  // public void onDestroyActionMode(ActionMode mode) {
  // mListview.clearChoices();
  // }
  //
  // @Override
  // public void onItemCheckedStateChanged(ActionMode mode, int position,
  // long id, boolean checked) {
  //
  // mode.invalidate();
  // mAdapter.notifyDataSetChanged();
  // }
  //
  // }

  private void volleypostDelete(final AttendanceDetail item) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DEL_ATTENDANCE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", item.getId());
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        LogUtil.i("response=" + arg0);
        SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
        if (result.getResult().equalsIgnoreCase(SuccessMessage.SUCCESS)) {
          ToastUtil.show("删除成功");
          //noinspection unchecked
          mAdapter.remove(item);
          mAdapter.notifyDataSetChanged();
          //updateSignInfo();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("删除失败");
      }
    });
  }

  @Override public void click(View v) {
    switch (v.getId()) {
      case R.id.ll_swipe://滑动删除
        int position = (Integer) v.getTag();

        final AttendanceDetail item = (AttendanceDetail) mAdapter.getItem(position);

        showDialog(item);
        break;
      case R.id.iv_photo://展示图片
        String filePath = (String) v.getTag();
        //String relativePath="100014_北京信普达系统工程有限公司/app/o_enterpriseforum_main/1F6E70A2-42AB-4CE2-A27B-E98D952765BF/4C81479F-76AD-4BF3-9CAA-EF61D744C0C5.jpg";
        Intent intent = new Intent(getActivity(), CompanyForumPictureActivity.class);
        intent.putExtra(CompanyForumPictureFragment.EXTRA_PICTUREA, filePath);
        intent.putExtra(CompanyForumPictureFragment.TYPE, CompanyForumPictureFragment.TYPEA);
        startActivity(intent);
        break;
    }
  }

  /**
   * 更新打卡详情页面的信息
   */
  @SuppressWarnings("unused") private void updateSignInfo() {
    int count = mAdapter.getCount();
    if (count == 0) return;
    Date in = null;
    Date out = null;
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    for (int i = 0; i < count; i++) {
      AttendanceDetail detail = ((AttendanceDetail) mAdapter.getItem(i));
      if (detail == null) continue;
      long checkTime = detail.getCheckTime();
      if (checkTime < cal.getTimeInMillis()) break;
      switch (detail.getCheckType()) {
        case 0:
          if (in == null) in = new Date(checkTime);
          if (checkTime < in.getTime()) in.setTime(checkTime);
          break;
        case 1:
          if (out == null) out = new Date(checkTime);
          if (checkTime > out.getTime()) out.setTime(checkTime);

          break;
      }
    }
    mCallbacks.onSignInfoUpdate(in, out);
  }

  public interface Callbacks {
    /**
     * 更新今日签到签退信息
     */
    void onSignInfoUpdate(Date signIn, Date singOut);
  }
}
